﻿using System;
using System.Windows;
using System.Windows.Controls;
using jSLCore.Client.Utility;

namespace jSLCore.Client.Presentation.BaseControl.Validation
{
    /// <summary>
    /// Показывает ошибку от jBinding
    /// </summary>
    public partial class ErrorBlock : UserControl
    {
        public ErrorBlock()
        {
            InitializeComponent();
            Loaded+=OnLoaded;
        }

        private bool isLoaded = false;

        /// <summary>
        /// null - означает все группы, "" - означает группу по умолчанию
        /// </summary>
        public string BindingGroupName { get; set; }

        private string _baseControlName;
        public string BaseControlName
        {
            get { return _baseControlName; }
            set
            {
                if (isLoaded)
                UnbindToBaseControl(FindName(_baseControlName) as BaseControl);
                _baseControlName = value;
                if (isLoaded)
                BindToBaseControl(FindName(_baseControlName) as BaseControl);
            }
        }

        private BaseControl _baseControl;
        public BaseControl BaseControl
        {
            get { return _baseControl; }
            set
            {
                if (isLoaded)
                UnbindToBaseControl(_baseControl);
                _baseControl = value;
                if(isLoaded)
                BindToBaseControl(_baseControl);
            }
        }


        private void OnLoaded(object sender, RoutedEventArgs routedEventArgs)
        {
            isLoaded = true;


            BaseControl baseControl = null;

            if(!string.IsNullOrEmpty(BaseControlName))
                baseControl = (BaseControl)FindName(BaseControlName);
            if (BaseControl != null)
                baseControl = BaseControl;
            if(baseControl==null)
            baseControl = this.FindAncestor<Presentation.BaseControl.BaseControl>() as BaseControl;
            
            BindToBaseControl(baseControl);
        }

        private void BindToBaseControl(BaseControl baseControl)
        {
            if(baseControl!=null)
            {
                baseControl.FirstErrorChanged += FirstErrorChanged;
                UpdateError(baseControl);
            }
        }

        

        private void UnbindToBaseControl(BaseControl baseControl)
        {
            if (baseControl != null)
            {
                baseControl.FirstErrorChanged -= FirstErrorChanged;
                UpdateError(baseControl);
            }
        }

        private void FirstErrorChanged(object sender, EventArgs e)
        {
            UpdateError((BaseControl) sender);
        }

        private void UpdateError(BaseControl sender)
        {
            txt.Text = sender.GetFirstError(BindingGroupName);
        }
    }
}
